<template>
  <div class="role-view-page">
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>角色查询</span>
        </div>
      </template>
      <el-form :model="queryForm" :inline="true" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="queryForm.rolename" placeholder="请输入角色名称" clearable style="width: 200px"
            @keyup.enter="handleSearch" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>角色列表</span>
          <el-button type="primary" link @click="fetchRoleList" :loading="loading">
            刷新
          </el-button>
        </div>
      </template>
      <el-button type="success" style="margin: 12px;" @click="Open('')">新增</el-button>
      <el-button type="danger" style="margin: 12px;" :disabled="selectedRoles.length === 0" @click="handleBatchDelete">
        批量删除 ({{ selectedRoles.length }})
      </el-button>
      <el-table v-loading="loading" :data="roleList" border stripe style="width: 100%" :height="500"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="rolenumber" label="角色编号" width="150" align="center" />
        <el-table-column prop="rolename" label="角色名称" width="150" align="center" />
        <el-table-column prop="roleorder" label="显示顺序" width="120" align="center" />
        <el-table-column prop="rolestatus" label="显示状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.rolestatus == 1 || row.rolestatus == '1'" type="success">
              启用
            </el-tag>
            <el-tag v-else type="danger">
              禁用
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="roledesc" label="角色备注" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.pageindex" v-model:page-size="pagination.pagesize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>

  <el-dialog draggable v-model="logic.IsOpen" :title="logic.Title" width="500">
    <el-form :label-width="120">
      <el-form-item label="角色名称">
        <el-input v-model="models.rolename" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色编号">
        <el-input v-model="models.rolenumber" placeholder="请输入角色编号" />
      </el-form-item>
      <el-form-item label="显示顺序">
        <el-input-number v-model="models.roleorder" :min="0" placeholder="请输入显示顺序" style="width: 100%" />
      </el-form-item>
      <el-form-item label="显示状态">
        <el-radio-group v-model="models.rolestatus">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="角色备注">
        <el-input v-model="models.roledesc" type="textarea" :rows="3" placeholder="请输入角色备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="logic.IsOpen = false">取消</el-button>
        <el-button type="primary" @click="AddRole">
          完成
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import https from '@/Http/http'
import { ElMessage, ElMessageBox } from 'element-plus'

interface RoleDto {
  id: number
  rolename: string
  rolenumber: string
  roleorder: number
  rolestatus: string
  roledesc: string
}

interface QueryForm {
  rolename?: string
}

interface Pagination {
  pageindex: number
  pagesize: number
  totalCount: number
  pageCount: number
}


const loading = ref(false)
const roleList = ref<RoleDto[]>([])
const selectedRoles = ref<RoleDto[]>([])

const queryForm = reactive<QueryForm>({
  rolename: ''
})

const pagination = reactive<Pagination>({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0,
  pageCount: 0
})

const getStatusCode = (payload: any) => payload?.code ?? payload?.Code
const getPayloadData = <T,>(payload: any): T => payload?.data ?? payload?.Data
const getPayloadMsg = (payload: any): string => payload?.msg ?? payload?.Msg ?? ''

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    const params: any = {
      pageindex: pagination.pageindex,
      paegsize: pagination.pagesize  // 注意：后端参数名是 paegsize（拼写错误）
    }

    if (queryForm.rolename) {
      params.rolename = queryForm.rolename
    }

    const { data } = await https.Reads.get(`/RBAC/ShowRole`, { params })

    if (getStatusCode(data) === 1) {
      // ApiPageing格式: { Code, Msg, TotalCount, PageCount, Data }
      roleList.value = data.Data || data.data || []
      pagination.totalCount = data.TotalCount || data.totalCount || 0
      pagination.pageCount = data.PageCount || data.pageCount || 0
    } else {
      ElMessage.error(getPayloadMsg(data) || '获取角色列表失败')
      roleList.value = []
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('无法获取角色列表，请检查服务是否可用')
    roleList.value = []
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  pagination.pageindex = 1
  fetchRoleList()
}

// 重置
const handleReset = () => {
  queryForm.rolename = ''
  pagination.pageindex = 1
  fetchRoleList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  
  pagination.pageindex = 1
  fetchRoleList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageindex = val
  fetchRoleList()
}

// 表格选择变化
const handleSelectionChange = (selection: RoleDto[]) => {
  selectedRoles.value = selection
}

// 打开对话框
const logic: any = reactive({
  IsOpen: false,
  Title: "",
  IsAdd: false
})

const models: any = reactive({
  Id: null,
  rolename: "",
  rolenumber: "",
  roleorder: 0,
  rolestatus: 1,
  roledesc: ""
})

const Open = (row: any) => {
  logic.IsOpen = true;
  if (row == '') {
    logic.Title = "新增";
    logic.IsAdd = true;
    models.Id = null;
    models.rolename = "";
    models.rolenumber = "";
    models.roleorder = 0;
    models.rolestatus = 1;
    models.roledesc = "";
  } else {
    logic.Title = "编辑";
    logic.IsAdd = false;
    models.Id = row.id;
    models.rolename = row.rolename;
    models.rolenumber = row.rolenumber;
    models.roleorder = row.roleorder;
    // 确保 rolestatus 转换为数字类型
    models.rolestatus = row.rolestatus == 1 || row.rolestatus == '1' ? 1 : 0;
    models.roledesc = row.roledesc || "";
  }
}

// 新增/编辑角色
const AddRole = async () => {
  if (!models.rolename) {
    ElMessage.warning('请输入角色名称')
    return
  }
  if (!models.rolenumber) {
    ElMessage.warning('请输入角色编号')
    return
  }

  try {
    let url = '';
    let method = '';
    let data: any = {};

    let response;
    if (logic.IsAdd) {
      const data = {
        rolename: models.rolename,
        rolenumber: models.rolenumber,
        roleorder: models.roleorder,
        rolestatus: models.rolestatus.toString(),
        roledesc: models.roledesc
      };
      response = (await https.Writes.post("/RBAC/AddRole", data)).data;
    } else {
      const data = {
        Id: models.Id,
        rolename: models.rolename,
        rolenumber: models.rolenumber,
        roleorder: models.roleorder,
        rolestatus: models.rolestatus.toString(),
        roledesc: models.roledesc
      };
      response = (await https.Writes.put("/RBAC/UpdateRole", data)).data;
    }

    if (getStatusCode(response) === 1) {
      ElMessage.success(getPayloadMsg(response) || (logic.IsAdd ? '新增成功' : '更新成功'));
      logic.IsOpen = false;
      fetchRoleList();
    } else {
      ElMessage.error(getPayloadMsg(response) || (logic.IsAdd ? '新增失败' : '更新失败'));
    }
  } catch (error: any) {
    console.error('操作失败:', error);
    ElMessage.error(error.response?.data?.msg || error.message || '操作失败，请稍后重试');
  }
}

// 编辑
const handleEdit = (row: RoleDto) => {
  Open(row)
}

// 删除
const handleDelete = async (row: RoleDto) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色「${row.rolename}」吗？`,
      '提示',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )

    await deleteRoles([row.id])
  } catch {
    // 用户取消删除
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请先选择要删除的角色')
    return
  }

  try {
    const roleNames = selectedRoles.value.map(r => r.rolename).join('、')
    await ElMessageBox.confirm(
      `确定要删除以下 ${selectedRoles.value.length} 个角色吗？\n${roleNames}`,
      '批量删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )

    const ids = selectedRoles.value.map(r => r.id)
    await deleteRoles(ids)
  } catch {
    // 用户取消删除
  }
}

// 执行删除操作
const deleteRoles = async (ids: number[]) => {
  try {
    if (ids.length === 1) {
      // 单个删除
      const { data } = await https.Writes.delete("/RBAC/DelRole", {
        data: { id: ids[0] }
      })

      if (getStatusCode(data) === 1) {
        ElMessage.success(getPayloadMsg(data) || '删除成功')
        selectedRoles.value = []
        fetchRoleList()
      } else {
        ElMessage.error(getPayloadMsg(data) || '删除失败')
      }
    } else {
      // 批量删除
      const { data } = await https.Writes.delete("/RBAC/DelAllRole", {
        data: { ids: ids }
      })

      if (getStatusCode(data) === 1) {
        const count = data.data || data.Data || ids.length
        ElMessage.success(`成功删除 ${count} 个角色`)
        selectedRoles.value = []
        fetchRoleList()
      } else {
        ElMessage.error(getPayloadMsg(data) || '删除失败')
      }
    }
  } catch (error: any) {
    console.error('删除失败:', error)
    ElMessage.error(error.response?.data?.msg || error.message || '删除失败，请稍后重试')
  }
}

onMounted(() => {
  fetchRoleList()
})
</script>

<style scoped>
.role-view-page {
  padding: 20px;
  background: #f5f6f8;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-card,
.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.search-form {
  margin-top: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

